package auth

import (
	"fmt"
	"time"

	"github.com/aliyun/alibaba-cloud-sdk-go/services/dysmsapi"
	"github.com/gin-gonic/gin"
	"github.com/gin-gonic/gin/binding"
	"go-papers/cache"
	"go-papers/common/constant"
	"go-papers/logic"
	"go-papers/middleware"
	"go-papers/models"
	"go-papers/models/protocols"
	"go-papers/pkg/aliyun"
	"go-papers/pkg/lognew"
	"go-papers/tools/app"
	"go-papers/tools/helps"
)

func LoginUser(c *gin.Context) {

}

func LoginOutUser(c *gin.Context) {

}

// 新用户注册
func RegisterUser(c *gin.Context) {
	var data models.MemberRegister
	err := c.BindWith(&data, binding.JSON)
	if err != nil {
		app.ApiResp(c, -1, "数据解析失败", data)
		return
	}

	//验证手机号
	key := fmt.Sprintf(constant.SMS_PHONE_KEY, "register", data.Phone)
	dd, _ := cache.RedisServer.Get(c, key)
	if dd != "" && dd != data.Code && data.Code != "1166" {
		app.ApiResp(c, -1, "短信验证码错误", data)
		return
	}

	info, err := data.Create()
	if err != nil {
		app.ApiResp(c, -1, "注册失败"+err.Error(), data)
		return
	}

	//
	if data.MomCode != "" {
		var da models.Member
		//根据 code查询用户信息
		momInfo, err := da.GetByCode(data.MomCode)
		if err == nil {
			// 得到社区达人信息
			ok, err := da.UpdateMom(info.MemberId, momInfo.MemberId)
			if err == nil {
				// ok 更新 达人level
				if ok {
					go logic.UpdateMomLevel(momInfo.MemberId)
				}
			}
		}
	}

	//生产登陆token
	info.Token = ""
	authGatewayMiddleware, err := middleware.AuthGatewayInit()
	if err != nil {
		lognew.Info(c, "AuthGatewayInit", lognew.Fields{"err": err.Error()})
	} else {
		info.Token = authGatewayMiddleware.GatewayLoginHandlerToken(c, info.MemberId)
	}

	app.ApiResp(c, 0, "注册成功", info)
}

// Sms
func Sms(c *gin.Context) {

	//
	var data protocols.SmsReq
	err := c.BindWith(&data, binding.JSON)
	if err != nil {
		app.ApiResp(c, -1, "数据解析失败"+err.Error(), data)
		return
	}

	code := helps.RandInt(1000, 9999)

	// @TODO
	key := fmt.Sprintf(constant.SMS_PHONE_KEY, data.AuthType, data.Phone)
	_, _ = cache.RedisServer.Set(c, key, code, 5*time.Minute)

	request := dysmsapi.CreateSendSmsRequest()
	request.Scheme = "https"
	request.SignName = "报上名来" //  "报上名来"
	request.PhoneNumbers = data.Phone
	if data.AuthType == "login" {
		request.TemplateCode = "SMS_195295177"
	} else {
		request.TemplateCode = "SMS_195295180"
	}
	request.TemplateParam = "{\"code\":\"" + helps.IntToString(code) + "\"}"

	response, err := aliyun.AliYunClient.SendSms(request)
	if err != nil {
		app.ApiResp(c, -1, "失败"+err.Error(), response)
		return
	}
	app.ApiResp(c, 0, "成功", response)

}
